// component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var Viewer: any;
@Component({
    selector: 'sa-trailer-manage',
    templateUrl: './trailer-manage.component.html',
    styleUrls: ['./trailer-manage.css']
})
export class TrailerManageComponent implements OnInit {
    tableData: any = []; // table的表单数据
    totalCounts: number = 0; //分页总条数
    curPage: number = 1; //分页当前页
    pageSize: number = 10; //内置的分页每页条数
    searchKey: any = ""; // 用户的搜索关键字
    carNumber: any = ""
    deviceId: any = "" //关联车头查询的设备id
    carNumber2: any = ""
    carId: any = "" //挂车车牌查询的ID
    carTypeList = carTypeListObj.carTypeList
    TcarUseList = carTypeListObj.carUseList
    TcarDeatailUseList = carTypeListObj.carDeatailUseList

    constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
        activatedRoute.queryParams.subscribe(queryParams => {
        });
    }
    ngOnInit() {
        var that = this;
        System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
            System.import('assets/js/select2-zh-CN.js').then(() => {
                that.initCar();
                that.initCar2();
            })
        });

        this.load();
    }

    // 获取列表数据
    load() {
        let param = {
            "pageSize": this.pageSize,
            "nowPage": this.curPage,
            "parameters": {
                searchKey: common.stringTrim(this.searchKey),
                export: '0',
                deviceId: this.deviceId,
                id: this.carId,
                useTypeL2: $('#TcarTypeSelect2').val() ? $('#TcarTypeSelect2').val() : '',
                useTypeL1: $('#TcarTypeSelect2').val() ? $('#TcarTypeSelect2').val().slice(0, 2) : ''
            }
        }
        let reqdata = 'gridPager=' + JSON.stringify(param);
        this.jsonApiService.http("TrailerCar/page.html", reqdata).subscribe(result => {
            let data = []
            if (result.isSuccess && result.exhibitDatas) {
                data = result.exhibitDatas

                this.tableData = result.exhibitDatas
                this.totalCounts = result.recordCount;

                for (let item of result.exhibitDatas) {
                    // item.useTypeLKey = item.useTypeL2;//车辆类型转换为中文
                    // item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);//车辆类型转换为中文
                    item.useTypeLKey = this.getUseTypeNameL2(item.useTypeL2);//车辆类型转换为中文
                }
            }
        });
    }
    //根据编码映射对应车辆类型名称
    getUseTypeNameL1(key) {
        if (key) {
            return this.TcarUseList[key];
        } else {
            return '';
        }
    }
    //根据编码映射对应车辆类型名称
    getUseTypeNameL2(key) {
        if (key) {
            return this.TcarDeatailUseList[key];
        } else {
            return '';
        }
    }

    // 分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
    // 刷新表
    refresh() {
        this.load();
    }
    // 表单查询
    tableSearch() {
        this.curPage = 1;
        this.load();
    }


    //初始化车辆
    initCar() {
        var that = this;
        $("#carNumberSelect").select2({
            language: "zh-CN",
            minimumInputLength: 2,
            allowClear: true,
            placeholder: "请选择",
            ajax: {
                url: config.BaseURL + "TrailerCar/list.html",
                dataType: 'json',
                delay: 100,
                method: "POST",
                xhrFields: { withCredentials: true },
                data: function (params) {
                    let param = {
                        "headstockNumber": params.term
                    }
                    let reqdata = {
                        data: JSON.stringify(param)
                    };
                    return reqdata;
                },
                processResults: function (data, params) {
                    var options = new Array();
                    // 小于10个数量才判断重复
                    if (data.data.length <= 10) {
                        let arr = []
                        let sameCar = []
                        // 判断相同的车牌号
                        for (let index = 0; index < data.data.length; index++) {
                            let car = data.data[index];
                            if (arr.indexOf(car.headstockNumber) != -1) {
                                sameCar.push(car.headstockNumber)
                            } else {
                                arr.push(car.headstockNumber);
                            }
                        }
                        $(data.data).each(function (index, car) {
                            if (sameCar.indexOf(car.headstockNumber) != -1) {
                                options.push({
                                    id: car.deviceId,
                                    text: car.headstockNumber + "[" + car.parentName + "]"
                                })
                            } else {
                                options.push({
                                    id: car.deviceId,
                                    text: car.headstockNumber
                                })
                            }
                        });
                    } else {
                        $(data.data).each(function (index, car) {
                            options.push({
                                id: car.deviceId,
                                text: car.headstockNumber
                            })
                        });
                    }
                    return {
                        results: options //获取查询后的结果
                    };
                },
                cache: true
            },
            templateResult: function (state) {
                if (!state.id) { return state.text; }
                var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                return $state;
            },
        }).on("select2:select", function (e) {
            var data = e.params.data;
            that.deviceId = data.id;
            if (data.text.indexOf('[') > 0) {
                that.carNumber = data.text.split('[')[0];
            } else {
                that.carNumber = data.text;
            }
        });

    }

    //清除车辆选中值
    del_carNumber() {
        this.carNumber = '';
        this.deviceId = '';
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect').val("");
        $("#select2-carNumberSelect-container").empty();
        $("#select2-carNumberSelect-container").attr("title", "");
        $("#select2-carNumberSelect-container").prepend(str);
    }

    //初始化车辆
    initCar2() {
        var that = this;
        $("#carNumberSelect2").select2({
            language: "zh-CN",
            minimumInputLength: 2,
            allowClear: true,
            placeholder: "请选择",
            ajax: {
                url: config.BaseURL + "TrailerCar/list.html",
                dataType: 'json',
                delay: 100,
                method: "POST",
                xhrFields: { withCredentials: true },
                data: function (params) {
                    let param = {
                        "trailerCarNumber": params.term
                    }
                    let reqdata = {
                        data: JSON.stringify(param)
                    };
                    return reqdata;
                },
                processResults: function (data, params) {
                    var options = new Array();
                    // 小于10个数量才判断重复
                    if (data.data.length <= 10) {
                        let arr = []
                        let sameCar = []
                        // 判断相同的车牌号
                        for (let index = 0; index < data.data.length; index++) {
                            let car = data.data[index];
                            if (arr.indexOf(car.trailerCarNumber) != -1) {
                                sameCar.push(car.trailerCarNumber)
                            } else {
                                arr.push(car.trailerCarNumber);
                            }
                        }
                        $(data.data).each(function (index, car) {
                            if (sameCar.indexOf(car.trailerCarNumber) != -1) {
                                options.push({
                                    id: car.id,
                                    text: car.trailerCarNumber + "[" + car.parentName + "]"
                                })
                            } else {
                                options.push({
                                    id: car.id,
                                    text: car.trailerCarNumber
                                })
                            }
                        });
                    } else {
                        $(data.data).each(function (index, car) {
                            options.push({
                                id: car.id,
                                text: car.trailerCarNumber
                            })
                        });
                    }
                    return {
                        results: options //获取查询后的结果
                    };
                },
                cache: true
            },
            templateResult: function (state) {
                if (!state.id) { return state.text; }
                var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                return $state;
            },
        }).on("select2:select", function (e) {
            var data = e.params.data;
            that.carId = data.id;
            if (data.text.indexOf('[') > 0) {
                that.carNumber2 = data.text.split('[')[0];
            } else {
                that.carNumber2 = data.text;
            }
        });

    }

    //清除车辆选中值
    del_carNumber2() {
        this.carNumber2 = '';
        this.carId = "";
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect2').val("");
        $("#select2-carNumberSelect2-container").empty();
        $("#select2-carNumberSelect2-container").attr("title", "");
        $("#select2-carNumberSelect2-container").prepend(str);
    }

    /**
     * 图片查看的方法
     */
    imgList: any = [];
    imgLocalList: any = [];
    isViewer2: boolean = false; //默认隐藏
    //显示图片组件
    viewer2: any = '';
    showImg2(row, modal) {

        this.imgList = [];
        this.imgLocalList = [];
        if (row.trailerCarImg.indexOf(',') > 1) {
            this.imgList = row.trailerCarImg.split(',');
        } else {
            this.imgList.push(row.trailerCarImg);
        }


        let localImg;
        for (var i = 0; i < this.imgList.length; i++) {
            if (this.imgList[i].indexOf('http') == -1) {
                if (this.imgList[i][0] == '/') {
                    localImg = config.BaseURL + this.imgList[i].substr(1);
                } else {
                    localImg = config.BaseURL + this.imgList[i];
                }
            } else {
                localImg = this.imgList[i];
            }
            this.imgLocalList.push(localImg);
        }
        modal.show();

        if (this.isViewer2 && $(".viewer-container").length > 0) {
            this.viewer2.destroy();
        }
    }
    // 关闭图片查看
    closeImgModal2(modal) {
        modal.hide();
        this.imgList = [];
        this.imgLocalList = [];
    }
    //图片放大
    bigimg(type, row) {
        this.showBigImg(type);
    }
    showBigImg(type) {
        var that = this;
        var imgList
        if (type == 'Modal2') {
            imgList = $(".imagesInfo2")[0];
            this.viewer2 = new Viewer(imgList, {
                url: 'src',
                title: function (image) {
                    return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
                },
            });
            that.isViewer2 = true
        }
    }

    pageType: any = '添加'
    //编辑
    edtrRecord(row, modal) {
        //清除数据
        for (let key in this.recordDetailFrom) {
            this.recordDetailFrom[key] = ''
        }
        this.pageType = '编辑';
        for (let key in row) {
            this.recordDetailFrom[key] = row[key] ? row[key] : '';
        }
        if (this.recordDetailFrom.trailerCarImg) {
            this.imageInfoList = this.recordDetailFrom.trailerCarImg.split(',');
        } else {
            this.imageInfoList = [];
        }
        this.recordDetailFrom.id = row.id;
        modal.show()
        $("#recordDetailForm").data("bootstrapValidator").resetForm();
        $("#select2-trailerManageSelect2-container").html('<span class="select2-selection__clear">×</span>' + row.headstockNumber)
    }
    deleteRecord(row) {
        this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
            this.jsonApiService.http("TrailerCar/deleteById.html", 'id=' + row.id).subscribe(data => {
                this.jsonApiService.message(data.message);
                if (data.success) {
                    this.load();
                }
            })
        })
    }

    //添加 操作
    recordDetailFrom: any = {
        id: '',
        headstockNumber: '',
        deviceId: '',
        trailerCarNumber: '',
        trailerCarImg: '',
        useTypeL2: '',
        useTypeL1: ''
    }
    syncrecordDetailOptions = {
        excluded: [":disabled"],
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            trailerCarNumber: {
                validators: {
                    notEmpty: {
                        message: '请输入挂车车牌'
                    }
                }
            },
            carUseType: {
                trigger: "change",
                validators: {
                    notEmpty: {
                        message: '请选择车辆类型'
                    }
                }
            }
        }
    }
    // 添加挂车管理
    addRecordDetail(modal) {
        this.pageType = '添加';
        for (let key in this.recordDetailFrom) {
            this.recordDetailFrom[key] = ''
        }
        this.imageInfoList = [];
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#trailerManageSelect2').val("");
        $("#select2-trailerManageSelect2-container").empty();
        $("#select2-trailerManageSelect2-container").attr("title", "");
        $("#select2-trailerManageSelect2-container").prepend(str);
        modal.show();
        $("#recordDetailForm").data("bootstrapValidator").resetForm();
    }
    //车辆用途change回调
	carUseTypeL1Change(){
        if(this.recordDetailFrom.useTypeL2){
            this.recordDetailFrom.useTypeL1 = this.recordDetailFrom.useTypeL2.slice(0, 2)
        }
        $("#recordDetailForm").data("bootstrapValidator").resetForm();
	}
    // 车辆组件数据回调
    optionSelected(data) {
        this.recordDetailFrom.headstockNumber = data.text;
        this.recordDetailFrom.deviceId = data.id;
    }
    recordDetailClose(modal) {
        for (let key in this.recordDetailFrom) {
            this.recordDetailFrom[key] = ''
        }
        modal.hide()
    }
    recordDetailSubmit(modal) {
        var Url;
        $('#recordDetailForm').bootstrapValidator('validate'); //开启验证
        let isValid = $('#recordDetailForm').data('bootstrapValidator').isValid();  //验证是否通过
        if (isValid) {
            if(!this.recordDetailFrom.trailerCarImg){
                this.jsonApiService.message('请上传挂车牌号图片');
                return
            }
            if(!this.recordDetailFrom.useTypeL2){
                this.jsonApiService.message('车辆类型为必填项');
                return
            }
            if (this.pageType == '添加') {
                Url = 'TrailerCar/add.html'
                delete this.recordDetailFrom.id
            } else if (this.pageType == '编辑') {
                Url = 'TrailerCar/edit.html'
            }

            let reqdata = 'data=' + JSON.stringify(this.recordDetailFrom)
            this.jsonApiService.http(Url, reqdata).subscribe(data => {
                this.jsonApiService.message(data.message);
                if (data.success) {
                    this.load();
                    modal.hide()
                }
            })
        }

    }


    imageInfoList: any = []; //图片数组
    fileList: File = null;
    //上传多张
    multifileChange(files: FileList) {
        if (this.isViewer && $(".viewer-container").length > 0) {
            this.viewer.destroy();
        }

        var that = this;
        let multfileList = files;

        var reqdata = new FormData();
        reqdata.append('describe', '挂车车牌');
        reqdata.append('businessType', '1');
        // reqdata.append('deviceId', this.page.deviceId);
        reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径

        for (var i = 0; i < multfileList.length; i++) {
            this.fileList = multfileList[i];
            const isJPG = this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png';
            if (!isJPG) {
                this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
                return;
            }

            reqdata.append('files', multfileList[i]);

        }

        that.jsonApiService.form_http("fileUpload/upload.html", reqdata).subscribe(data => {
            if (data.success) {
                for (var i = 0; i < data.data.length; i++) {
                    that.imageInfoList.push(data.data[i]);
                }
                this.recordDetailFrom.trailerCarImg = this.imageInfoList.join(',');
            }
        })


        for (let k = 0; k < $(".up").length; k++) {
            $(".up")[k].value = null;
        }

    }
    //删除
    deleteImg(i) {
        this.imageInfoList.splice(i, 1);
        this.recordDetailFrom.trailerCarImg = this.imageInfoList.join(',');

        if (this.isViewer && $(".viewer-container").length > 0) {
            this.viewer.destroy();
        }
    }
    bigImg: any = '' //
    isViewer: boolean = false; //默认隐藏
    bigImgClick(img) {
        // modal.show();
        this.bigImg = img;
        if (this.isViewer && $(".viewer-container").length > 0) {
            System.import('assets/js/viewer/viewer.js').then(
                () => {
                    System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                        () => {
                            System.import('assets/js/viewer/viewer.css').then(() => {
                                this.showImg();
                            })
                        })
                })
        } else {
            this.showImg();
        }


    }
    //显示图片组件
    viewer: any = '';
    showImg() {
        var that = this;
        var imgList = $(".imgFileList")[0];
        this.viewer = new Viewer(imgList, {
            url: 'src',
            title: function (image) {
                return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
            },
        });
        that.isViewer = true
    }


    // 同步车辆
    // 同步项目车辆的表单
    syncCarvalidatorOptions = {
        excluded: [":disabled"],
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            syncCompany: {
                trigger: "change",
                validators: {
                    notEmpty: {
                        message: '请选择平台'
                    }
                }
            },
        }
    }
    // 同步车辆的参数
    sourceType: any = ""; // 选择的要同步的公司
    //打开弹窗
    openSyncCarModal(modal) {
        this.sourceType = ""
        $("#syncCarFrom").data("bootstrapValidator").resetForm();
        modal.show();
    }
    // 关闭弹窗
    syncCarClose(modal) {
        $("#syncCarFrom").data("bootstrapValidator").resetForm();
        modal.hide();
    }
    // 提交要同步的公司
    submitSyncCar(modal) {
        $('#syncCarFrom').bootstrapValidator('validate'); //开启验证
        let isValid = $('#syncCarFrom').data('bootstrapValidator').isValid();  //验证是否通过
        if (isValid) {
            let reqdata = "sourceType=" + this.sourceType;
            this.jsonApiService.http('TrailerCar/synchronization.html', reqdata).subscribe(data => {
                this.jsonApiService.message(data.message);
                if (data.success) {
                    this.load();
                }
                this.syncCarClose(modal);
            })
        }
    }
}